package com.fancy.controller.api;

import com.fancy.config.WechatMpConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import com.lly835.bestpay.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLEncoder;
import java.util.Map;

/**
 * 微信公众公众账号api
 * Created by FancyFong on 8/9/2017.
 */
@Controller
@Slf4j
public class WechatApiController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private BestPayService bestPayService;

    @Autowired
    private WechatMpConfig wecatMpConfig;


    /**
     * 微信授权
     * 链接构造
     * @param url
     */
    @GetMapping("/api/wechat/authorize")
    public String authorize(@RequestParam("returnUrl") String url){

        //1.配置 WechatMpConfig
        String redirectUri = wecatMpConfig.getUserInfoUrl();

        //2.调用方法
        String redirect = wxMpService.oauth2buildAuthorizationUrl(redirectUri,WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(url));
        log.info("【微信页面授权】获取code，result={}",redirect);

        return "redirect:" + redirect;
    }

    /**
     * 通过code
     * 获取openId
     * 获取userInfo
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/api/wechat/userInfo")
    public String userInfo(@RequestParam("code") String code,
                         @RequestParam("state") String state){

        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();

        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        }catch (WxErrorException e){
            log.error("【微信页面授权】获取AccessToken异常，result={}",e);
        }

        WxMpUser wxMpUser = new WxMpUser();
        try {
            wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken,null);
        }catch (WxErrorException e){
            log.error("【微信页面授权】获取getUserInfo异常，result={}",e);
        }


        log.info("【微信页面授权】getUserInfo={}",wxMpUser.toString());

        return "redirect:" + state + "?openid=" + wxMpUser.getOpenId();
    }


    /**
     * 微信公众号支付
     * @param map
     * @return
     */
    @GetMapping("/api/wechat/h5Pay")
    public ModelAndView h5Pay(Map<String, Object> map){
        PayRequest request = wecatMpConfig.setPayRequest(BestPayTypeEnum.WXPAY_H5,"123",0.01,"最好的支付sdk","1234");
        log.info("【发起支付】request={}", JsonUtil.toJson(request));

        PayResponse payResponse = bestPayService.pay(request);
        log.info("【发起支付】response={}", JsonUtil.toJson(payResponse));

        map.put("payResponse", payResponse);
        return new ModelAndView("pay/create", map);
    }


    /**
     * 异步回调
     */
    @PostMapping(value = "/notify")
    public ModelAndView notify(@RequestBody String notifyData) throws Exception {
        log.info("【异步回调】request={}", notifyData);


        PayResponse response = bestPayService.asyncNotify(notifyData);
        log.info("【异步回调】response={}", JsonUtil.toJson(response));

        return new ModelAndView("pay/success");
    }




}
